import React, { useEffect, useState } from 'react'
import useGetTableData from '@/hooks/useGetTableData'
import { queryPurchaseGoods, createBoxLabelList } from '@/api/purchase'
import SearchForm from '@/components/CustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { QueryPurchaseGoodsVO as ITableData } from './types'
import CustomTable from '@/components/CustomTable'
import { useNavigate } from 'react-router-dom'
import { useBoxMarkAddColumns } from './columns'
import './BoxConfig.less'
import { Button, Empty, message, notification, Space } from 'antd'
import { getSpuOptions } from '@/api/goods'
import { PlusOutlined } from '@ant-design/icons'
import { onValuesChange } from '@/utils/onValuesChange'
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  const navigate = useNavigate()
  const [form] = useForm()
  const [selectKeys, setselectKeys] = useState<React.Key[]>([])
  const [selectInfos, setselectInfos] = useState<ITableData[]>([])
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [SkuOptions, setSkuOptions] = useState<IOptionItem[]>([])
  const [tableData, settableData] = useState<ITableData[]>([])
  const [exportLoading, setexportLoading] = useState(false)
  const { tableProps, params, setParams, search, reset } = useGetTableData<ITableData>(queryPurchaseGoods, {
    form: form,
  })
  useEffect(() => {
    settableData(tableProps.dataSource)
  }, [tableProps.dataSource])

  const selectRows = (keys: React.Key[], info: ITableData[]) => {
    setselectKeys(keys)
    setselectInfos(info)
  }

  const handleAddBoxMark = async () => {
    if (selectKeys.length === 0) {
      message.warning('请选择需要新建的箱唛并且填入本次新建数量！')
      return
    }
    const items = tableData?.filter((item) => item.createQty > 0)
    if (items.length === 0) {
      message.warning('请选择需要新建的箱唛并且填入本次新建数量！')
      return
    }
    const paramsData = {
      detailDTOList: items?.map((item) => {
        return {
          skuCode: item.skuCode,
          spuCode: item.spuCode,
          purchaseOrderCode: item.purchaseOrderCode || '',
          supplierId: item.supplierId || '',
          createQty: item.createQty,
        }
      }),
    }
    setexportLoading(true)
    const res = await createBoxLabelList(paramsData).finally(() => {
      setexportLoading(false)
      search(params)
      setselectKeys([])
      setselectInfos([])
    })
    if (res.code === 200) {
      message.success('操作成功')
      navigate('/scan/boxmark/list')
    }
    if (res.code === 820000 && res.failInfo) {
      const failInfo = JSON.parse(res.failInfo)?.map((item: any) => {
        return (
          <div key={item.purchaseCode + item.skuCode}>
            purchaseCode：{item.purchaseCode}，skuCode：{item.skuCode}
          </div>
        )
      })
      notification.open({
        type: 'warning',
        message: res.msg,
        description: failInfo,
      })
    }
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data = res.data?.map((item) => {
          return {
            label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
            value: item.spuCode,
          }
        })
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }

  return (
    <PageContainer className="purchase_boxmarkadd_page">
      <SearchForm
        params={params}
        form={form}
        onValuesChange={(changedValues) => onValuesChange(changedValues, ['purchaseOrderCode'], form)}
        searchConfig={[
          { label: '采购订单号', name: 'purchaseOrderCode', type: 'Input' },
          {
            label: 'SPU商品',
            name: 'spuCode',
            type: 'Select',
            option: SpuOptions,
            placeholder: '款式编码/款式名称/助记码/工厂款号',
            config: {
              suffixIcon: null,
              showSearch: true,
              filterOption: false,
              optionFilterProp: 'label',
              onSearch: handleSearchSpuOptions,
              notFoundContent: <Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />,
            },
          },
          {
            label: 'SKU商品',
            name: 'skuCodeList',
            placeholder: '商品条码',
            type: 'Select',
            option: SkuOptions,
            config: {
              mode: 'tags',
              maxTagCount: 'responsive',
              notFoundContent: null,
            },
          },
        ]}
        onFinish={(vals: any) => {
          setselectKeys([])
          setselectInfos([])
          search(vals)
        }}
        onReset={() => {
          setselectKeys([])
          setselectInfos([])
          reset()
        }}
        extra={
          <div className="table_extra_flex">
            <Button type="primary" onClick={handleAddBoxMark} icon={<PlusOutlined />} loading={exportLoading}>
              新建箱唛
            </Button>
          </div>
        }
      ></SearchForm>
      <CustomTable
        bordered
        rowKey={(row) => row.purchaseOrderCommodityId}
        columns={useBoxMarkAddColumns({ selectKeys, setselectKeys, tableData, settableData })}
        {...tableProps}
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectKeys}
      />
    </PageContainer>
  )
}

export default Index
